import { Context } from 'vm';
import Koa from "koa";
import { JWT } from '../config/constant';
import jwt from 'jsonwebtoken';
import { Interface } from 'readline';

/*获取当前ip地址*/
export const getIpAddress = () => {
  const interfaces = require('os').networkInterfaces()
  for (const devName in interfaces) {
    const temp = interfaces[devName]
    for (let i = 0; i < temp.length; i++) {
      const alias = temp[i]
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address
      }
    }
  }
}

// 获取客户端ip地址
export const getClientIpAddress = (ctx: Context) => {
  const headers = ctx.headers
  if (headers['x-forwarded-for']) {
    const ipList = headers['x-forwarded-for'].split(',')
    return ipList[0]
  }
  return '0.0.0.0'
}

// 通过token解析userId
export const decodeToken = (token: string) => {
  let jwtInfo = jwt.verify(token, JWT.secret) as any
  try {
    return jwtInfo.userId
  } catch (err) {
    return 'token不合法'
  }

}

// 根据userId生成token
export const generatorToken = (userId: number) => {
  return jwt.sign({ userId }, JWT.secret, { expiresIn: JWT.expires })

}


export interface IRouteOption {
  prefix?: string;
  path: string;
  method: 'get' | 'post';
  handlers: {[key: string]: Function };
} 
export const injectRouter = (router: any, options: Array<IRouteOption>) => {
    options.forEach(config => {
      const { prefix, path, method, handlers } = config;
      for (const key in handlers) {
        if (Object.prototype.hasOwnProperty.call(handlers, key)) {
          const handler = handlers[key];
          router[method](`${prefix || ''}${path}/${key}`, handler);
          console.log(`注入路由: ${method.toUpperCase()} ${prefix || ''}${path}/${key}`);
        }
      }
    })
}

export const createPromise = (): { resolve: any; reject: any; promise: Promise<any>; } => {
  let resolve = null;
  let reject = null;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { resolve, reject, promise };
}